import Testing
import Foundation
@testable import IAPDFKit

@Test func example() async throws {
    // Write your test here and use APIs like `#expect(...)` to check expected conditions.
}

// MARK: - 合并单页面 测试
@Test func mergeSinglePDF() async throws {
    let bundle = Bundle.module
    guard let fileURL = bundle.url(forResource: "222", withExtension: "pdf") else {
        #expect(Bool(false), "Missing test resource")
        return
    }

    do {
        let task = try await IAPDFKit.shared.mergeSinglePage(fileURL, onProgress: { progress in
            print("Progress: \(progress)")
        })
        
        let outputURL = try await task.value
        
        print("Merged PDF URL: \(outputURL)")
        
        let isOk = FileManager.default.fileExists(atPath: outputURL.path)
        
        #expect(Bool(isOk))
    } catch {
        #expect(Bool(false), "Error \(error)")
    }
}

// MARK: - 合并单页面 取消测试
@Test func testMergeSinglePDFCancel() async throws {
    let bundle = Bundle.module
    guard let fileURL = bundle.url(forResource: "333", withExtension: "pdf") else {
        #expect(Bool(false), "Missing test resource")
        return
    }

    do {
        // 创建任务
        let task = try await IAPDFKit.shared.mergeSinglePage(fileURL, onProgress: { progress in
            print("Progress: \(progress)")
        })

        // 延迟一小段时间让任务开始执行
        Task.detached {
            try? await Task.sleep(nanoseconds: 50_000_000) // 50ms
            task.cancel() // 主动取消
        }

        // 等待任务结果
        _ = try await task.value
        
        // 如果没有抛出异常，则失败
        #expect(Bool(false), "Task should have been cancelled")
    } catch IAPDFError.cancel {
        // 预期取消错误
        #expect(Bool(true))
    } catch {
        // 其他错误
        #expect(Bool(false), "Unexpected error: \(error.localizedDescription)")
    }
}
